package com.vitas.coin.ui.dialog;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.vitas.coin.R;
import java.lang.ref.WeakReference;


/**
 * 加载中Dialog
 *
 */
public class LoadingDialog extends AlertDialog{
	private String progressText;
	private TextView tips_loading_msg;
	//创建 Handler
	final MyHandler myHandler = new MyHandler(this);

	private static class MyHandler extends Handler {
		private final WeakReference<LoadingDialog> weakReference;

		public MyHandler(LoadingDialog dialog) {
			this.weakReference = new WeakReference<>(dialog);
		}

		@Override
		public void handleMessage(@NonNull Message msg) {
			if (weakReference == null) {
				return;
			}

			LoadingDialog dialog = weakReference.get();
			if (null != dialog) {
				if (msg.what == 1001) {
					int progress = msg.arg1;
					if (dialog.tips_loading_msg != null) {
						dialog.tips_loading_msg.setText(dialog.progressText + progress + "%");
					}
				}
			}
		}

	}


	public LoadingDialog(Context context) {
		super(context, R.style.loadingStyle);
	}

	public void setProgressText(String progressText){
		this.progressText = progressText;
		if (tips_loading_msg!=null) {
			tips_loading_msg.setText(TextUtils.isEmpty(progressText)?"上传中...":progressText);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dialog_loading_cus);
		tips_loading_msg = findViewById(R.id.tips_loading_msg);
		tips_loading_msg.setText(TextUtils.isEmpty(progressText)?"上传中...":progressText);
	}


	@Override
	public void onBackPressed() {

	}


	public void onProgress(int progress) {
		Message message = myHandler.obtainMessage();
		message.what = 1001;
		message.arg1 = progress;
		myHandler.sendMessage(message);
	}

}
